# @Time : 2024/7/19 9:42
# @Author : Adam
# @Version : v1.0
# @IDE : PyCharm
# @Project : tracer
"""
用户账户想关功能：注册、短信、登录、注销
"""
import uuid
import datetime
from django.shortcuts import render, HttpResponse, redirect, reverse
from web.forms.account import RegisterModelForm, SendEmailForm, LoginEmailForm, LoginForm
from django.core.mail import send_mail
from django.http import JsonResponse
from web import models
from utils.image_code import check_code
from io import BytesIO
from django.db.models import Q


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库(密码要是密文)
        # 用户表中新建了一条数据（注册）
        instance = form.save()

        policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        # 方式二
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_email(request):
    """发送邮件"""
    # email = request.GET.get('email')
    # tpl = request.GET.get('tpl')  # register/login

    form = SendEmailForm(request, data=request.GET)
    # 只是校验邮箱：不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_email(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginEmailForm()
        return render(request, 'login_email.html', {'form': form})
    form = LoginEmailForm(data=request.POST)
    if form.is_valid():
        user_object = form.cleaned_data['email']
        # 用户信息放入session

        # 把用户名写入到session中

        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username
        print(user_object)
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'statue': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """用户名和密码"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        # （手机=username and pwd=pwd）or (邮箱=username and pwd=pwd)

        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            # 用户名密码正确
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    image_object, code = check_code()
    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60秒
    stream = BytesIO()
    image_object.save(stream, 'png')
    print(code)
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect(reverse('index'))
